package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Pest.cropPestReportDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.CameraCropMapping;
import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.pear.MainPestPear;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.pear.PlantDiseasePredictionResult;
import com.tbvtc.agriculturalcreditchainserver2025.service.ICameraCropMappingService;
import com.tbvtc.agriculturalcreditchainserver2025.service.IpfsService;
import com.tbvtc.agriculturalcreditchainserver2025.service.PestService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestConstant;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestHttpUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Pest.getCropPestReportVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("admin/Pest")
@CrossOrigin
@Tag(name = "病虫害管理")
public class PestController {
    @Autowired
    private PestHttpUtils pestHttpUtils;
    @Resource
    private PestUtils pestUtils;
    @Autowired
    private PestService pestService;
    @Autowired
    private IpfsService ipfsService;
    @Autowired
    private ICameraCropMappingService cameraCropService;
    @Resource(name = "stringRedisTemplate")
 private StringRedisTemplate redisTemplate;

    /**
     * 病虫害识别
     *
     * @return
     */
    @Operation(summary = "获取草莓摄像头图片")
    @PostMapping
    public Result Pest() {
        String captureImage = pestHttpUtils.getCaptureImage(120, 900);
        return getResult(captureImage);
    }

    /**
     * 添加病虫害报告
     *
     * @param crropReportDto
     * @return
     * @throws IOException
     */
    @Operation(summary = "添加病虫害报告")
    @PostMapping("/addPestReport")
    public Result PestReport(@RequestBody cropPestReportDto crropReportDto) throws IOException {
        pestService.addPestReport(crropReportDto);
        return RUtils.success();
    }

    /**
     * 获取病虫害报告
     *
     * @param cropName
     * @return
     */
    @Operation(summary = "获取病虫害报告")
    @GetMapping("/getPestReport")
    public Result getPestReport(@RequestParam String cropName) {
        List<getCropPestReportVo> pestReport = pestService.getPestReport(cropName);
        return RUtils.success(pestReport);
    }

    @Operation(summary = "修改摄像头监控的农作物")
    @PutMapping
    public Result updatePestReports(@RequestBody CameraCropMapping cameraCropMapping) {
        cameraCropService.updateById(cameraCropMapping);
        return RUtils.success();
    }

    @Operation(summary = "草莓是否具有病虫害报告")
    @PostMapping("/isPest")
    public Result isPest(@RequestParam String hash) {
        byte[] bytes = new RestTemplate().getForObject(PestConstant.ipfsURL + hash, byte[].class);
        return RUtils.success(pestHttpUtils.uploadImage(bytes, PestConstant.fileName));
    }



    @Operation(summary = "获取梨树是否具有病虫害")
    @PostMapping("/pearIsPest")
    public Result pearIsPest(@RequestParam String hash) {
        byte[] bytes = new RestTemplate().getForObject(PestConstant.ipfsURL + hash, byte[].class);
        String json = pestHttpUtils.uploadPearImage(bytes, PestConstant.fileName);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            PlantDiseasePredictionResult result = objectMapper.readValue(json, PlantDiseasePredictionResult.class);
            MainPestPear mainPestPear = BeanUtil.copyProperties(result, MainPestPear.class);
            return RUtils.success(mainPestPear);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    @Operation(summary = "获取梨摄像头图片")
    @GetMapping("/pearPestImage")
    public Result pearPest() {
        String captureImage = pestHttpUtils.getPearCaptureImage();

//        String image="Qmb8iuU32bLgXRn5v9adWApep7Wqz8SmorJj5nJb3DgZ6Y";
        return getResult(captureImage);

    }

    @NotNull
    private Result getResult(String captureImage) {
        JsonObject jsonObject = JsonParser.parseString(captureImage).getAsJsonObject();
        String url = jsonObject.get("url").getAsString();
        String lastPart = StringUtils.substringAfterLast(url, "/");
        String absolutePath = "F:\\农信链python\\OpencvRTSP\\captured_images\\" + lastPart;
        try {
            String hash = ipfsService.uploadToIpfs(absolutePath);
            return RUtils.success(hash);
        } catch (IOException e) {
            throw new FoodException(ResultCodeEnum.FAILED_TO_UPLOAD);
        }
    }

    @Operation(summary = "返回抓拍图片")
    @GetMapping("/returnImage")
    public Result returnImage() {
        try {
            String hash = redisTemplate.opsForValue().get(RedisConstant.PEST_IMAGE);
            return RUtils.success(hash);
        } catch (NullPointerException e) {
            throw new FoodException(ResultCodeEnum.FILE_NOT_FOUND);
        }
    }
}
